package com.dianshang.elasticsearch;

import org.apache.http.HttpHost;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.TermQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.builder.SearchSourceBuilder;

/**
 * 搜索引擎(ElasticSearch)
 */
public class ElasticSearch5Demo {

    /**
     * 过滤查询
     * 筛选性别为男的记录
     */
    public static void main(String[] args) throws Exception {
        // 1、创建一个restClient客户端,用于访问ES
        HttpHost httpHost = new HttpHost("127.0.0.1", 9200,"http"); // hostname：本机地址,port：端口号,scheme：HTTP协议
        RestClientBuilder restClientBuilder = RestClient.builder(httpHost); // rest客户端构建器
        RestHighLevelClient restHighLevelClient = new RestHighLevelClient(restClientBuilder); // rest高级客户端
        // 2、创建一个对应行为的请求对象
        SearchRequest searchRequest = new SearchRequest("zhaoyu"); // 获取索引库名
        searchRequest.types("doc"); // 获取类型名称
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder(); // 封装查询条件
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery(); // 布尔查询构建器
        TermQueryBuilder termQueryBuilder = QueryBuilders.termQuery("sex", "男"); // 获取查询条件
        boolQueryBuilder.filter(termQueryBuilder); // 用来封装查询条件
        searchSourceBuilder.query(boolQueryBuilder); // 用来封装查询条件
        searchRequest.source(searchSourceBuilder); // 存入封装后的查询条件/设置查询条件构造器
        // 3、触发请求,获取响应结果
        SearchResponse searchResponse = restHighLevelClient.search(searchRequest,RequestOptions.DEFAULT);
        // 4、使用响应的结果
        SearchHits searchHits = searchResponse.getHits(); // 获取所有符合要求的数据
        long totalHits = searchHits.getTotalHits(); // 获取所有符合要求的条数
        System.out.println("记录数："+totalHits);
        SearchHit[] hits = searchHits.getHits(); // 展示符合要求的所有数据
        for (SearchHit hit : hits) { // 循环遍历符合要求的所有数据
            String s = hit.getSourceAsString();
            System.out.println(s);
        }
        // 5、关闭ES客户端
        restHighLevelClient.close();
    }

}